#!/usr/bin/env python
# -*- coding: utf-8 -*-
#===============================================================================
# Copyright 2011 zod.yslin
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 
# Author: zod.yslin
# Email: 
# File Name: encapsulation.py
# Description: 
#   希望做到良好的資訊隱藏 (information hiding) ，也就是說我們不要讓類別定義以外
#   的地方，存取屬性值，這時，我們可以將屬性設定為私有的，簡單來說，就是在
#   屬性識別字 (identifier) 名稱前加上連續兩個底線符號。
#   
#   Python does not really support encapsulation because it does not support 
#   data hiding through private and protected members. However some pseudo-encapsulation 
#   can be done. If an identifier begins with a double underline, i.e. __a, then it 
#   can be referred to within the class itself as self.__a, but outside of the class, 
#   it is named instance._classname__a. Therefore, while it can prevent accidents, 
#   this pseudo-encapsulation cannot really protect data from hostile code.
# Edit History: 
#   2011-08-10    File created.
#===============================================================================
class Demo:
    __x = 0 # private class attribute
 
    def __init__(self, i):
        self.__i = i
        Demo.__x += 1
     
    def __str__(self):
        return str(self.__i)
          
    def hello(self):
        print("hello", self.__i)
     
    @classmethod
    def getX(cls):
        return cls.__x
 
a = Demo(9527)
a.hello() 
print("Demo.__x =", Demo.getX())  # 1
print("Demo.__x =", Demo._Demo__x)  # 1, pseudo-encapsulation
#print("a.__i =", a.__i)  # error
print("a.__i =", a._Demo__i)  # 9527, pseudo-encapsulation
